package com.zhoudy.apizuul.filters;


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.ServletInputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StreamUtils;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;

public class PreRequestFilter extends AbstractZuulFilter {


    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext context = RequestContext.getCurrentContext();

            InputStream in = (InputStream) context.get("params");
            if (in == null) {
                in = context.getRequest().getInputStream();
            }

//			String b = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
//			logger.info("body:" + b);

            String token = context.getRequest().getParameter("token");

            logger.info("accessToken:" + token);
            logger.info("params:" + context.getRequestQueryParams());
            logger.info("contentLength:" + context.getRequest().getContentLength());
            logger.info("contentType:" + context.getRequest().getContentType());

            // token 为空不处理
            if (StringUtils.isNotBlank(token)) {
//
                // 校验成功
                String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
                logger.info("body:" + body);
//					body = StringUtils.replace(body, PARAM_TOKEN + "=" + token, PARAM_TOKEN + "=" + authResult.getToken());
//					logger.info("转换后的body：" + body);
                // context.set("requestEntity", new
                // ByteArrayInputStream(body.getBytes("UTF-8")));
                final byte[] reqBodyBytes = body.getBytes();
                context.setRequest(new HttpServletRequestWrapper(RequestContext.getCurrentContext().getRequest()) {
                    @Override
                    public ServletInputStream getInputStream() throws IOException {
                        return new ServletInputStreamWrapper(reqBodyBytes);
                    }

                    @Override
                    public int getContentLength() {
                        return reqBodyBytes.length;
                    }

                    @Override
                    public long getContentLengthLong() {
                        return reqBodyBytes.length;
                    }
                });
                return null;
            }
//			if (responseHandler != null) {
//				context.getResponse().setCharacterEncoding("UTF-8");
//				context.setResponseStatusCode(responseHandler.getResponseCode());
//				context.setResponseBody(responseHandler.getResponseBody(null, null));
//			}

            context.setSendZuulResponse(false);

            // body = "request body modified via set('requestEntity'): "+ body;
            // String reqBody = body + "-appendUserSuffix";
            // final byte[] reqBodyBytes = reqBody.getBytes();
            // logger.info("accessToken:" + reqBody);
            //
            // // context.set("requestEntity", new
            // // ByteArrayInputStream(body.getBytes("UTF-8")));
            // context.setRequest(new
            // HttpServletRequestWrapper(getCurrentContext().getRequest()) {
            // @Override
            // public ServletInputStream getInputStream() throws IOException {
            // return new ServletInputStreamWrapper(reqBodyBytes);
            // }
            //
            // @Override
            // public int getContentLength() {
            // return reqBodyBytes.length;
            // }
            //
            // @Override
            // public long getContentLengthLong() {
            // return reqBodyBytes.length;
            // }
            // });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


}
